package com.xiangxiangjd.utils.document;

import com.aspose.words.Document;
import com.aspose.words.SaveFormat;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author LF
 * @date 2020/8/26 - 16:46
 *  刘飞
 */
public class WordToPDF {

    public static String toPDF(MultipartFile file,String fileDir){
        FileOutputStream outSTr = null;
        BufferedOutputStream Buff = null;
        //获取文件名字
        String filename = file.getOriginalFilename();
        //System.out.println(filename+"===filename");
        //本地文件暂存路径
        //String oldfile= "C:\\CCC\\";  //fileDir代替oldfile,因为写入完成需要上传后再删除暂存文件或文件夹
        //截取后缀
        String suffix = filename.substring(0,filename.lastIndexOf("."));
        //本地pdf文件暂存
        String pdfurl= fileDir+suffix+".pdf";
        try {
            File myPath = new File( fileDir );
            if ( !myPath.exists()){//若此目录不存在，则创建之
                myPath.mkdir();
                System.out.println("创建文件夹路径为："+ fileDir);
            }

            //经过测试：BufferedOutputStream执行耗时:1,1，1 毫秒
            //创建文件输出
            outSTr = new FileOutputStream(new File(fileDir+filename));
            //缓冲流
            Buff = new BufferedOutputStream(outSTr);
            //开始写入时间
            long begin0 = System.currentTimeMillis();
            //写入文件
            Buff.write(file.getBytes());
            //刷新
            Buff.flush();
            //关闭
            Buff.close();
            //结束写入时间
            long end0 = System.currentTimeMillis();
            //文件写入耗时
            System.out.println("BufferedOutputStream执行耗时:" + (end0 - begin0) + " 毫秒");


            //doc路径
            Document document = new Document(fileDir+filename);
            //pdf路径
            File outputFile = new File(pdfurl);
            //System.out.println(outputFile.getPath()+"===outputFile.getPath()");
            //操作文档保存
            document.save(outputFile.getAbsolutePath(), SaveFormat.PDF);

            //返回本地暂存的PDF路径
            return pdfurl;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                Buff.close();
                outSTr.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "";
    }

    public static void main(String[] args) throws IOException {
        try {
            //doc路径
            Document document = new Document("E:\\CCC\\经典风格java工程师黑色求职简历word简历模板.docx");
            //pdf路径
            File outputFile = new File("E:\\CCC\\经典风格java工程师黑色求职简历word简历模板.pdf");
            //操作文档保存
            document.save(outputFile.getAbsolutePath(), SaveFormat.PDF);
            System.out.println("success");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }



}
